#ifndef GAMELOGICH_H
#include "GameLogic.h"
#endif

GameLogic::GameLogic(const Data_Manager *data_manager,PaintSystem *paint_system):
    data_manager(data_manager),
    paint_system(paint_system)
{
    grid = new Grid();
    setupGrid();
    cargo_manager = new Cargo_Manager(paint_system);
    facility_manager = new Facility_Manager(cargo_manager);
    // map_data_manager = new Map_Data_Manager();

}

void GameLogic::setupGrid(){
    grid->data_manager = data_manager;
}

void GameLogic::logic_update(){
    facility_manager->update();
}

Facility* GameLogic::tryToPlaceFacility(FacilityType f_type, FacilityDirection f_dir, int group_idx, const Coordinate &co){

    if(!grid->isValid(co.x,co.y)){return null;}
    Facility * facility = facility_manager->generateFacilityWithTypeAndIdx(f_type,group_idx,f_dir,co);
    if(!facility){
        return null; // 没有定义
    }
    // 检查是否可以放置
    bool flag = grid->CanPlace(co,facility->width,facility->height);
    if(!flag){// 不可以放置
        facility_manager->deleteFacility(facility);
        return null;
    }
    // 可以放置后 记得 清理内部设施、记得连接周围设施
    for(auto &to_delete_f: grid->setFacility(facility,co,facility->width,facility->height)){
        facility_manager->deleteFacility(to_delete_f);
    }
    std::unordered_set<Facility*> fs = grid->surroundingFacilities(co,facility->width,facility->height);
    facility_manager->connnetFacilitys(facility,fs);

    // 如果是开采者，记得更新
    if(facility->define->getFacilityType() == FacilityType::MINER){
        facility_manager->updateMinerTarget(facility,
            data_manager->getGrid()[facility->coordinate.x][facility->coordinate.y]);
    }


    return facility;
}

void GameLogic::tryToRemoveFacility(const Coordinate &co){
    if(!grid->isValid(co.x,co.y)){return;}
    Facility *f = (*grid)[co].master;
    if(!f){return;}
    if(f->getFacilityType() == FacilityType::HUB){return;}
    grid->setFacility(null,co,f->width,f->height);
    facility_manager->deleteFacility(f);
}

void GameLogic::do_save(){
    // if(map_data_manager){map_data_manager->doSave();}
}
void GameLogic::load_save(){

    // map_data_manager = new Map_Data_Manager();
    // map_data_manager->loadSave();
}

GameLogic::~GameLogic(){
    if(grid) delete grid;
    if(facility_manager) delete facility_manager;
    if(cargo_manager) delete cargo_manager;
    // if(map_data_manager) delete map_data_manager;
    grid = null;
    facility_manager = null;
    cargo_manager = null;
    // map_data_manager = null;
}
